import {
	baseUrl
} from '@/utils/config';
import {
	cleanLogin,
	getTicket
} from './auth';

export default {
	config: {
		baseUrl,
		appCode: `61xrk0n2l2pc5lcrsnhq`
	},
	showToast: (msg) => {
		uni.showToast({
			title: msg || '请求失败',
			icon: 'none',
			duration: 2000
		})
	},
	//封装uni.request()
	request(options) {
		options.header = this.config.header
		options.url = this.config.baseUrl + options.url
		options.data = {
			...(options.data || {}),
			ticket: getTicket(),
			app_code: this.config.appCode
		}
		uni.showLoading({
			title: '加载中'
		})
		return new Promise((resolve, reject) => {
			//书写异步操作的代码
			uni.request({
				...options,
				success: res => {
					uni.hideLoading()
					if (res.statusCode === 200) {
						if (res.data.status === 1000) {
							resolve([res.data.data, void 0])
						} else {
							this.showToast(res.data.msg)
							reject([void 0, res])
						}
					} else {
						this.showToast(res.data.msg)
						reject([void 0, res])
					}
				},
				fail: err => {
					cleanLogin()
					uni.hideLoading()
					reject([void 0, err])
				}
			})
		})
	},
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}
}